package com.magenta.maxoptra.abstractions;

import java.util.Hashtable;

import javax.naming.NamingException;
import javax.naming.NoInitialContextException;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;
import javax.naming.spi.NamingManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static javax.naming.Context.*;

/**
 * Singleton.
 * @author ivictus
 *
 */
public class ServiceInitialContextFactoryBuilder implements
		InitialContextFactoryBuilder {

	private static final Logger LOG = LoggerFactory.getLogger(ServiceInitialContextFactoryBuilder.class);

	private static ServiceInitialContextFactoryBuilder instance;

	private ServiceInitialContextFactoryBuilder() { }

	public static ServiceInitialContextFactoryBuilder getInstance() {
		synchronized (ServiceInitialContextFactoryBuilder.class) {
			if (instance == null) {
				instance = new ServiceInitialContextFactoryBuilder();
			}
		}
		return instance;
	}

	@Override
	public InitialContextFactory createInitialContextFactory(
			Hashtable<?, ?> environment) throws NamingException {
		String className;
		InitialContextFactory factory;
		if ((className = (String) environment.get(INITIAL_CONTEXT_FACTORY)) != null) {
            try {
                factory = (InitialContextFactory)
                	Thread.currentThread().getContextClassLoader().loadClass(className).newInstance();
            } catch(Exception e) {
                NoInitialContextException noInitialContextException =
                    new NoInitialContextException(
                        "Cannot instantiate class: " + className);
                noInitialContextException.setRootCause(e);
                throw noInitialContextException;
            }
		} else {
			factory = new ServiceInitialContextFactory(environment);
		}
		return factory;
	}

	static {
		try {
			NamingManager.setInitialContextFactoryBuilder(new ServiceInitialContextFactoryBuilder());
		} catch (NamingException e) {
			LOG.error("INITIALIZATION OF CONTEXT FACTORY BUILDER FAILED!", e);
		}
	}

}
